#!/bin/bash

#############################################################
# 前端项目构建与Docker镜像发布脚本
#############################################################
# 
# 功能说明:
#   1. 构建前端项目
#   2. 创建Docker镜像
#   3. 推送镜像到Docker仓库
#
# 参数选项:
#   -D: 跳过项目构建阶段，直接构建Docker镜像
#   -P: 自动推送镜像到Docker仓库
#   -E: 从环境变量读取所有配置信息，而非交互式输入
#   -C: 构建完成后清理本地Docker镜像
#   -N: 不安装依赖，直接构建（适用于CI环境）
#
# 环境变量:
#   基本环境变量:
#   IMAGE_NAME: Docker镜像名称 (默认: "rbac-admin-frontend")
#   IMAGE_TAG: Docker镜像标签 (默认: 当前时间戳)
#
#   当使用 -E 参数时需要设置:
#   DOCKER_REGISTRY: Docker仓库地址
#   DOCKER_USERNAME: Docker仓库账号
#   DOCKER_PASSWORD: Docker仓库密码
#
# 使用示例:
#   1. 完整流程(构建项目 -> 构建镜像)，交互式输入:
#      ./build.sh
#
#   2. 跳过项目构建，仅构建Docker镜像:
#      ./build.sh -D
#
#   3. 构建项目和镜像，并推送到Docker仓库:
#      ./build.sh -P
#
#   4. 跳过项目构建，构建Docker镜像并推送:
#      ./build.sh -D -P
#
#   5. 使用环境变量自动化构建并推送:
#      export IMAGE_NAME="my-custom-image"
#      export DOCKER_REGISTRY="registry.example.com"
#      export DOCKER_USERNAME="username"
#      export DOCKER_PASSWORD="password"
#      ./build.sh -P -E
#
#   6. 构建后清理本地镜像:
#      ./build.sh -C
#
#############################################################

# 解析命令行参数
SKIP_BUILD=false
PUSH_IMAGE=false
USE_ENV_VARS=false
CLEAN_IMAGES=false
SKIP_INSTALL=false

while getopts "DPECN" opt; do
  case $opt in
    D)
      SKIP_BUILD=true
      ;;
    P)
      PUSH_IMAGE=true
      ;;
    E)
      USE_ENV_VARS=true
      ;;
    C)
      CLEAN_IMAGES=true
      ;;
    N)
      SKIP_INSTALL=true
      ;;
    \?)
      echo "无效参数: -$OPTARG" >&2
      exit 1
      ;;
  esac
done

# 检查pnpm是否可用
if ! command -v pnpm &> /dev/null; then
  echo "错误: 未找到pnpm"
  echo "请安装pnpm并确保它在PATH环境变量中"
  exit 1
fi

# 设置变量
DEFAULT_IMAGE_NAME="rbac-admin-frontend"
DEFAULT_IMAGE_TAG=$(date +"%Y%m%d%H%M")
LATEST_TAG="latest"

# 根据是否使用环境变量来设置配置
if [ "$USE_ENV_VARS" = true ]; then
  # 使用环境变量
  
  # 检查必要的环境变量
  if [ "$PUSH_IMAGE" = true ]; then
    if [ -z "$DOCKER_REGISTRY" ]; then
      echo "错误: 使用 -E 参数时，环境变量 DOCKER_REGISTRY 必须设置"
      exit 1
    fi
    
    if [ -z "$DOCKER_USERNAME" ] || [ -z "$DOCKER_PASSWORD" ]; then
      echo "错误: 使用 -E 参数时，环境变量 DOCKER_USERNAME 和 DOCKER_PASSWORD 必须设置"
      exit 1
    fi
  fi
  
  # 设置镜像名称
  IMAGE_NAME=${IMAGE_NAME:-$DEFAULT_IMAGE_NAME}
  
  # 设置镜像标签
  IMAGE_TAG=${IMAGE_TAG:-$DEFAULT_IMAGE_TAG}
  
else
  # 交互式输入
  echo "====================================================="
  echo "  前端项目构建与Docker镜像发布脚本 - 配置"
  echo "====================================================="

  # 镜像名称
  echo -n "请输入镜像名称: "
  read -r input_name
  IMAGE_NAME=${input_name:-$DEFAULT_IMAGE_NAME}
  
  # 镜像标签
  echo -n "请输入镜像标签 [${DEFAULT_IMAGE_TAG}]: "
  read -r input_tag
  IMAGE_TAG=${input_tag:-$DEFAULT_IMAGE_TAG}
  
  # 如果需要推送镜像，获取Docker仓库信息
  if [ "$PUSH_IMAGE" = true ]; then
    echo -n "请输入Docker仓库地址: "
    read -r DOCKER_REGISTRY
    while [ -z "$DOCKER_REGISTRY" ]; do
      echo "Docker仓库地址不能为空，请重新输入:"
      read -r DOCKER_REGISTRY
    done
    
    echo -n "请输入Docker仓库用户名: "
    read -r DOCKER_USERNAME
    while [ -z "$DOCKER_USERNAME" ]; do
      echo "Docker仓库用户名不能为空，请重新输入:"
      read -r DOCKER_USERNAME
    done
    
    echo -n "请输入Docker仓库密码: "
    read -rs DOCKER_PASSWORD
    echo
    while [ -z "$DOCKER_PASSWORD" ]; do
      echo "Docker仓库密码不能为空，请重新输入:"
      read -rs DOCKER_PASSWORD
      echo
    done
  fi
fi

# 输出脚本信息
echo "====================================================="
echo "  前端项目构建与Docker镜像发布脚本"
echo "====================================================="
echo "镜像名称: ${IMAGE_NAME}:${IMAGE_TAG}"
if [ "$PUSH_IMAGE" = true ]; then
  echo "Docker仓库: ${DOCKER_REGISTRY}"
fi
echo "====================================================="
echo "跳过构建: ${SKIP_BUILD}"
echo "推送镜像: ${PUSH_IMAGE}"
echo "使用环境变量: ${USE_ENV_VARS}"
echo "清理镜像: ${CLEAN_IMAGES}"
echo "跳过依赖安装: ${SKIP_INSTALL}"
echo "====================================================="

# 进入项目根目录
cd ../../../

# 前端构建部分
if [ "$SKIP_BUILD" = true ]; then
  echo "[1/3] 跳过前端项目构建"
else
  echo "[1/3] 开始构建前端项目..."
  
  if [ "$SKIP_INSTALL" = false ]; then
    # 安装依赖
    echo "安装依赖..."
    pnpm install --frozen-lockfile
    if [ $? -ne 0 ]; then
      echo "依赖安装失败，退出脚本"
      exit 1
    fi
  else
    echo "跳过依赖安装..."
  fi

  # 构建前端项目
  echo "构建前端项目..."
  pnpm build
  if [ $? -ne 0 ]; then
    echo "前端项目构建失败，退出脚本"
    exit 1
  fi

  echo "前端项目构建成功"
fi

# 检查Dockerfile是否存在
if [ ! -f "apps/server-client/Dockerfile" ]; then
  echo "错误: 未找到Dockerfile"
  echo "请确保Dockerfile存在于apps/server-client目录"
  exit 1
fi

# 构建Docker镜像
echo "[2/3] 构建Docker镜像..."
cd apps/server-client
docker build -t ${IMAGE_NAME}:${IMAGE_TAG} -t ${IMAGE_NAME}:${LATEST_TAG} -f Dockerfile .

# 检查构建结果
if [ $? -ne 0 ]; then
  echo "Docker镜像构建失败，退出脚本"
  exit 1
fi

echo "Docker镜像构建成功"
echo "镜像信息:"
docker images | grep ${IMAGE_NAME}

# 推送镜像逻辑
if [ "$PUSH_IMAGE" = true ]; then
  echo "[3/3] 准备推送Docker镜像..."
  
  # 登录Docker仓库
  echo "正在登录Docker Registry..."
  echo "$DOCKER_PASSWORD" | docker login ${DOCKER_REGISTRY} -u "$DOCKER_USERNAME" --password-stdin
  
  if [ $? -ne 0 ]; then
    echo "Docker Registry登录失败，退出脚本"
    exit 1
  fi
  
  # 推送镜像
  echo "推送镜像到Docker仓库 ${DOCKER_REGISTRY}..."
  docker push "${IMAGE_NAME}:${IMAGE_TAG}"
  docker push "${IMAGE_NAME}:${LATEST_TAG}"
  
  echo "镜像推送完成"
else
  echo "[3/3] 跳过镜像推送"
fi

echo "====================================================="
echo "构建和发布流程已完成!"
echo "镜像地址: ${IMAGE_NAME}:${IMAGE_TAG}"
echo "镜像地址: ${IMAGE_NAME}:${LATEST_TAG}"
echo "====================================================="

# 清理本地镜像（如果启用）
if [ "$CLEAN_IMAGES" = true ]; then
  echo "清理本地Docker镜像..."
  docker rmi ${IMAGE_NAME}:${IMAGE_TAG}
  docker rmi ${IMAGE_NAME}:${LATEST_TAG}
  if [ "$PUSH_IMAGE" = true ]; then
    docker rmi ${REGISTRY_IMAGE_NAME}:${IMAGE_TAG}
    docker rmi ${REGISTRY_IMAGE_NAME}:${LATEST_TAG}
  fi
  echo "本地镜像清理完成"
fi

# 使用说明
echo "===== 使用说明 ====="
echo "运行容器示例:"
echo "docker run -d -p 80:80 -e BACKEND_API_URL=http://your-backend-api ${IMAGE_NAME}:${IMAGE_TAG}"
echo "====================================================="
